import '@/styles/LoginRegisterCommon.css';
import { useNavigate } from 'react-router-dom';
import React, { useState, useContext } from 'react';
import { message } from 'antd';
import { aesEcbEncrypt } from '@/utils/encrypt'; // 导入加密函数
import axios from 'axios';
import myImage1 from '@/assets/jpg/齿轮.png';
import myImage2 from '@/assets/jpg/齿轮.png';
import { EyeTwoTone , EyeInvisibleTwoTone } from '@ant-design/icons'; 

const Register = () => {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false); 
    const navigate = useNavigate();
    const [isAnimatedUsername, setIsAnimatedUsername] = useState(false);
    const [isAnimatedPassword, setIsAnimatedPassword] = useState(false);

    // 用户名正则：3-12位中英文、数字
    const uPattern = /^[\u4e00-\u9fa5a-zA-Z0-9]{3,12}$/;

    // 密码正则：6-20位，至少1个字母、1个数字
    const pPattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/;

    const handleFocus = (params) => {
        if (params === 'username') setIsAnimatedUsername(true);
        if (params === 'password') setIsAnimatedPassword(true);
    };

    const handleBlur = (params) => {
        if (params === 'username' && !username) setIsAnimatedUsername(false);
        if (params === 'password' && !password) setIsAnimatedPassword(false);
    };

    const handleSubmit = async (e) => {
        e.preventDefault(); // 阻止表单默认提交行为

        if (!username || !password) {
            message.error('用户名或密码不能为空');
            return;
        }
        // 检查用户名是否符合正则规则
        if (!uPattern.test(username)) {
            message.error('用户名必须是3-12位中英文或数字');
            return;
        }

        // 检查密码是否符合正则规则
        if (!pPattern.test(password)) {
            message.error('密码必须是8-20位，且包含字母和数字');
            return;
        }
        const key = "d8d73c9f91ad4fc689cf1dac563dc906"; // 16 字节密钥
        const ciphertext = await aesEcbEncrypt(password, key);
        const data = {
            username,
            password: ciphertext,
        };
        try {
            const response = await axios.post('/api/v1/account/register', data);
            
            if (response.data.code === 0) {
                localStorage.setItem('enc_token', response.data.data.token);
                localStorage.setItem('username', response.data.data.username);
                localStorage.setItem('privilege_level', 0);
                message.success('注册成功');
                navigate('/upload');
            }
            else {
                message.error(response.data.msg);
            }
        } catch (error) {
            console.error('注册请求发生错误:', error);
            message.error('注册失败，请稍后重试');
        }
    };

    const handleLoginClick = () => {
        navigate('/login');
    };

    const togglePasswordVisibility = () => {
        setShowPassword(!showPassword);
    };

    return (
        <div className="big">
            <div className="leftcircle circle" style={{
                display: 'flex',
                justifyContent: 'center', alignItems: 'center'
            }}>  <img src={myImage1} alt="description" width="60" /></div>
            <div className="conveyer leftconveyer"><span></span><span></span></div>
            <div className="container">
                <form onSubmit={handleSubmit}>
                    <h2>Register</h2>
                    <div className="item">
                        <input
                            type="text"
                            value={username}
                            onFocus={() => handleFocus('username')}
                            onBlur={() => handleBlur('username')}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                        <label className={isAnimatedUsername ? 'animated-class' : ''}>Username</label>
                    </div>
                    <div className="item" style={{ position: 'relative' }}>
                        <input
                            type={showPassword ? 'text' : 'password'}
                            onFocus={() => handleFocus('password')}
                            onBlur={() => handleBlur('password')}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                        />
                        <label className={isAnimatedPassword ? 'animated-class' : ''}>Password</label>
                        <span
                            onClick={togglePasswordVisibility}
                            style={{
                                position: 'absolute',
                                right: '10px',
                                top: '80%',
                                transform: 'translateY(-50%)',
                                cursor: 'pointer',
                                color: '#666'
                            }}
                        >
                            {showPassword ? <EyeTwoTone /> : <EyeInvisibleTwoTone />}
                        </span>
                    </div>
                    <button>Enter</button>
                    <div className="conversion" onClick={handleLoginClick}>
                        已有账号？前去登录
                    </div>
                </form>
            </div>
            <div className="conveyer rightconveyer"><span></span><span></span></div>
            <div className="rightcircle circle" style={{
                display: 'flex',
                justifyContent: 'center', alignItems: 'center'
            }}> <img src={myImage2} alt="description" width="60" /></div>
        </div>
    );
};

export default Register;